package com.hmall.gateway.filters;

import lombok.Data;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.OrderedGatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.factory.GatewayFilterFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * @author Administrator
 * @version 1.0
 * @description:
 * @date 2024/6/5 16:16
 */
// 注意事项
        //1、类名必须以【GatewayFilterFactory】结尾
        //2、配置文件中，路由过滤器名字跟类名前缀（GatewayFilterFactory前面那部分）一致
@Component
public class PrintAnyGatewayFilterFactory extends AbstractGatewayFilterFactory<PrintAnyGatewayFilterFactory.Config> {
    @Override
    public GatewayFilter apply(Config config) {
        return new OrderedGatewayFilter(new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                System.out.println("PrintAny 自定义路由过滤器执行了...");
                System.out.println("config.getA() = " + config.getA());
                System.out.println("config.getB() = " + config.getB());
                System.out.println("config.getC() = " + config.getC());
                return chain.filter(exchange);
            }
        },1);
    }

    /**
     * 1、定义一个静态类，用于封装接受来自yaml中配置的参数
     */
    @Data
    static class Config{
        private String a;
        private String b;
        private String c;
    }

    /**
     * 2、定义yaml中参数与config中属性的位置对应关系
     * @return
     */
    @Override
    public List<String> shortcutFieldOrder() {
        //Arrays.asList("a","b","c");
        return List.of("a","b","c");
    }

    /**
     * 3、委托父类将yaml中的参数读取到Config类中
     */
    public PrintAnyGatewayFilterFactory() {
        super(Config.class);
    }
}
